from scipy.stats import ks_2samp
from sklearn.metrics import make_scorer, roc_auc_score, log_loss
import random
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle


# 1 sort score 2 x total accumulate ratio y bad/good accumulate ratio
def ks_stat(y, yhat):
    ks = ks_2samp(yhat[y == 1], yhat[y != 1]).statistic
    ks_scorer = make_scorer(ks, needs_proba=True)
    return ks_scorer


l = []
for i in range(100):
    r = random.random()
    if r >= 0.5:
        l.append((random.random() * 100, 1))
    else:
        l.append((random.random() * 100, 0))
l.sort(key=lambda x: x[0])

total_all = len(l)
total_1 = len([i for i in l if i[1] == 1])
total_0 = len([i for i in l if i[1] == 0])


def coordinate(sub_l, total_all, total_1, total_0):
    x = len(sub_l) / total_all
    y0 = len([i for i in sub_l if i[1] == 0]) / total_0
    y1 = len([i for i in sub_l if i[1] == 1]) / total_1
    return (x, y0, y1)


xs = []
y0s = []
y1s = []
for index, v in enumerate(l):
    sub_l = l[:index + 1]
    (x, y0, y1) = coordinate(sub_l, total_all, total_1, total_0)
    xs.append(x)
    y0s.append(y0)
    y1s.append(y1)

plt.figure()
lw = 2
plt.plot(xs, y0s, color='darkorange', lw=lw, label='y0')
plt.plot(xs, y1s, color='green', lw=lw, label='y1')
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('Accumulate ration for all sample')
plt.ylabel('Accumulate ration for specific type')
plt.title('Score from low to high')
plt.legend(loc="lower right")
plt.show()
